import request from '../../utils/request';
Page({
    data: {
        money: 'x',
        teamMembers: [],
        // 分页相关参数
        pageNum: 1,
        pageSize: 10,
        total: 0,
        hasMore: true,
        loading: false
    },
    onLoad: function (options) {
        this.loadTeamData();
        this.loadConfig();
    },

    // 加载团队数据的方法
    loadTeamData: function (isRefresh = false) {
        // 如果是刷新，重置分页参数
        if (isRefresh) {
            this.setData({
                pageNum: 1,
                teamMembers: [],
                hasMore: true
            });
        }

        // 如果正在加载或没有更多数据，直接返回
        if (this.data.loading || !this.data.hasMore) {
            return;
        }

        this.setData({
            loading: true
        });

        request({
            url: 'api/myUser/getTeam',
            method: 'get',
            data: {
                pageNum: this.data.pageNum,
                pageSize: this.data.pageSize
            }
        }).then(res => {
            if (res.code == 200) {
                const newMembers = res.rows || [];
                const currentMembers = this.data.pageNum === 1 ? [] : this.data.teamMembers;

                this.setData({
                    teamMembers: [...currentMembers, ...newMembers],
                    total: res.total,
                    hasMore: newMembers.length === this.data.pageSize,
                    pageNum: this.data.pageNum + 1
                });
            }
        }).catch(err => {
            console.error('加载团队数据失败:', err);
            wx.showToast({
                title: '加载失败，请重试',
                icon: 'none'
            });
        }).finally(() => {
            this.setData({
                loading: false
            });

        });
    },

    // 加载配置信息的方法
    loadConfig: function () {
        request({
            url: 'api/login/getConfig',
        }).then(res => {
            if (res.data) {
                wx.setStorageSync('config', res.data);
                this.setData({
                    money: res.data.rewardAmount
                });
            }
        }).catch(err => {
            console.error('加载配置失败:', err);
        });
    },

    // 触底刷新事件
    onReachBottom: function () {
        console.log('触底加载更多数据');
        this.loadTeamData();
    },

    // 下拉刷新事件
    onPullDownRefresh: function () {
        console.log('下拉刷新');
        this.loadTeamData(true);
        // 停止下拉刷新动画
        setTimeout(() => {
            wx.stopPullDownRefresh();
        }, 1000);
    },

    onShow: function () { }
});